#pragma once
#include <iostream>
#include <string>
#include <cstdio>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

const std::string comm_path = "./myfifo";
#define Creator 1
#define User 2
#define Read O_RDONLY
#define Write O_WRONLY
#define DefautFd -1
#define BaseSize 4096

// 进行封装
class NamedPipe
{
private:
    bool OpenNamedPipe(int mode)
    {
        _fd = open(_fifo_path.c_str(), mode);
        if (_fd < 0)
            return false;
        return true;
    }

public:
    NamedPipe(const std::string fifo_path, int who)
        : _fifo_path(fifo_path), _id(who), _fd(DefautFd)
    {
        if (_id == Creator)
        {
            // 创建命名管道
            int res = mkfifo(_fifo_path.c_str(), 0666);
            if (res != 0)
            {
                perror("unlink: ");
            }
            std::cout << "Creator create named pipe!" << std::endl;
        }
    }

    bool OpenToRead()
    {
        return OpenNamedPipe(Read);
    }

    bool OpenToWrite()
    {
        return OpenNamedPipe(Write);
    }

    // * : 输出型参数
    int ReadNamedPipe( std::string* out)
    {
        char buffer[BaseSize];
        int n = read(_fd, buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            *out = buffer;
        }
        return n;
    }

    int WriteNamedPipe(const std::string& in)
    {
        return write(_fd, in.c_str(), in.size());
    }

    ~NamedPipe()
    {
        if (_id == Creator)
        {
            // sleep(6);
            // 删除命名管道
            int res = unlink(_fifo_path.c_str());
            if (res != 0)
            {
                perror("unlink: ");
            }
            std::cout << "Creator delete named pipe!" << std::endl;
        }

        // 两个用户各自关闭文件
        if(_fd != DefautFd) close(_fd);
    }

private:
    std::string _fifo_path; // 管道路径
    int _id;                // 使用管道的人的身份
    int _fd;
};
